from werkzeug.exceptions import HTTPException
from flask import request, json


class AdminException(HTTPException):
    pass


class ApiException(HTTPException):
    status = 500
    msg = 'mistakes'
    code = 999

    def __init__(self, msg=None, status=None, code=None, headers=None):
        if msg:
            self.msg = msg
        if status:
            self.status = status
        if code:
            self.code = code
        super(ApiException, self).__init__(msg, None)
        pass

    def get_body(self, environ=None):
        body = dict(
            code=self.code,
            msg=self.msg,
            request_uri=request.method+' '+self.get_url_no_param()
        )
        return json.dumps(body)

    def get_headers(self, environ=None):
        """Get a list of headers."""
        return [("Content-Type", "application/json")]

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split("?")
        return main_path[0]


class Success(ApiException):
    status = 201
    msg = 'ok'
    code = 0


class DeleteSuccess(Success):
    status = 204
    msg = 'deleted'
    code = -1


class ServerError(ApiException):
    status = 500
    msg = '内部出错了，抱歉了'
    code = 999


class ClientTypeException(ApiException):
    status = 400
    msg = 'invalid client type'
    code = 1006


class NotFoundException(ApiException):
    status = 404
    msg = 'not found the resource'
    code = 1001


class ParameterException(ApiException):
    status = 400
    msg = 'invalid parameter'
    code = 1000


class AuthFailedException(ApiException):
    status = 401
    msg = 'authorization failed'
    code = 1005
